import fs from '@ohos.file.fs';
import { path } from '@ohos.file.path';

// 游戏记录接口
export interface GameRecord {
  id: string;
  heroName: string;
  finalLevel: number;
  enemiesDefeated: number;
  totalExperience: number;
  duration: number; // 秒
  isVictory: boolean;
  timestamp: number;
}

// 游戏统计接口
export interface GameStatistics {
  totalGames: number;
  totalVictories: number;
  totalDefeats: number;
  highestLevel: number;
  mostEnemiesDefeated: number;
  totalPlayTime: number; // 秒
}

// 游戏存档接口
export interface GameSave {
  id: string;
  hero: {
    name: string;
    maxHealth: number;
    attack: number;
    defense: number;
    level: number;
    currentHealth: number;
    experience: number;
    experienceToNextLevel: number;
  };
  currentStage: number;
  bossesDefeated: number;
  turns: number;
  timestamp: number;
}

// JSON数据存储路径常量
const STORAGE_DIR = path.join(fs.getLocalDir(), 'game_data');
const GAME_RECORDS_FILE = path.join(STORAGE_DIR, 'game_records.json');
const GAME_STATS_FILE = path.join(STORAGE_DIR, 'game_stats.json');
const GAME_SAVES_DIR = path.join(STORAGE_DIR, 'saves');

// 初始化存储目录
async function initializeStorage(): Promise<void> {
  try {
    // 检查并创建主存储目录 - 修复fs.access的使用方式
    try {
      await fs.access(STORAGE_DIR);
    } catch (error) {
      // 文件不存在时创建目录
      await fs.mkdir(STORAGE_DIR, 0o755);
    }
    
    // 检查并创建存档目录
    try {
      await fs.access(GAME_SAVES_DIR);
    } catch (error) {
      await fs.mkdir(GAME_SAVES_DIR, 0o755);
    }
    
    // 创建默认的游戏记录文件
    try {
      await fs.access(GAME_RECORDS_FILE);
    } catch (error) {
      // 修复文件创建和写入方式
      const file = await fs.open(GAME_RECORDS_FILE, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
      await file.write(JSON.stringify([]));
      await file.close();
    }
    
    // 创建默认的游戏统计文件
    try {
      await fs.access(GAME_STATS_FILE);
    } catch (error) {
      const defaultStats: GameStatistics = {
        totalGames: 0,
        totalVictories: 0,
        totalDefeats: 0,
        highestLevel: 0,
        mostEnemiesDefeated: 0,
        totalPlayTime: 0
      };
      const file = await fs.open(GAME_STATS_FILE, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
      await file.write(JSON.stringify(defaultStats));
      await file.close();
    }
  } catch (error) {
    console.error('初始化存储失败:', error);
  }
}

// 游戏数据服务类
export class GameDataService {
  private isInitialized: boolean = false;

  // 初始化服务
  private async ensureInitialized(): Promise<void> {
    if (!this.isInitialized) {
      await initializeStorage();
      this.isInitialized = true;
    }
  }

  // 读取文件内容 - 修复文件读取方式
  private async readFileContent(filePath: string): Promise<string> {
    try {
      const file = await fs.open(filePath, fs.OpenMode.READ_ONLY);
      const fileInfo = await fs.stat(filePath);
      const buffer = new ArrayBuffer(fileInfo.size);
      await file.read(buffer);
      await file.close();
      return String.fromCharCode.apply(null, new Uint8Array(buffer));
    } catch (error) {
      console.error(`读取文件失败 ${filePath}:`, error);
      throw error;
    }
  }

  // 写入文件内容 - 修复文件写入方式
  private async writeFileContent(filePath: string, content: string): Promise<void> {
    try {
      const file = await fs.open(filePath, fs.OpenMode.CREATE | fs.OpenMode.WRITE_ONLY);
      await file.write(content);
      await file.close();
    } catch (error) {
      console.error(`写入文件失败 ${filePath}:`, error);
      throw error;
    }
  }

  // 获取游戏历史记录
  async getGameHistory(): Promise<GameRecord[]> {
    await this.ensureInitialized();
    try {
      const content = await this.readFileContent(GAME_RECORDS_FILE);
      return JSON.parse(content) as GameRecord[];
    } catch (error) {
      console.error('读取游戏记录失败:', error);
      return [];
    }
  }

  // 保存游戏记录
  async saveGameRecord(record: GameRecord): Promise<boolean> {
    await this.ensureInitialized();
    try {
      // 读取现有记录
      const records = await this.getGameHistory();
      // 添加新记录
      records.unshift(record); // 添加到开头
      // 写入文件
      await this.writeFileContent(GAME_RECORDS_FILE, JSON.stringify(records));
      // 更新统计信息
      await this.updateStatistics(record);
      return true;
    } catch (error) {
      console.error('保存游戏记录失败:', error);
      return false;
    }
  }

  // 获取游戏统计信息
  async getGameStatistics(): Promise<GameStatistics> {
    await this.ensureInitialized();
    try {
      const content = await this.readFileContent(GAME_STATS_FILE);
      return JSON.parse(content) as GameStatistics;
    } catch (error) {
      console.error('读取游戏统计失败:', error);
      return {
        totalGames: 0,
        totalVictories: 0,
        totalDefeats: 0,
        highestLevel: 0,
        mostEnemiesDefeated: 0,
        totalPlayTime: 0
      };
    }
  }

  // 更新统计信息
  private async updateStatistics(record: GameRecord): Promise<void> {
    const stats = await this.getGameStatistics();
    
    stats.totalGames++;
    if (record.isVictory) {
      stats.totalVictories++;
    } else {
      stats.totalDefeats++;
    }
    stats.highestLevel = Math.max(stats.highestLevel, record.finalLevel);
    stats.mostEnemiesDefeated = Math.max(stats.mostEnemiesDefeated, record.enemiesDefeated);
    stats.totalPlayTime += record.duration;
    
    await this.writeFileContent(GAME_STATS_FILE, JSON.stringify(stats));
  }

  // 保存游戏进度
  async saveGame(gameSave: GameSave): Promise<boolean> {
    await this.ensureInitialized();
    try {
      const saveFile = path.join(GAME_SAVES_DIR, `save_${gameSave.id}.json`);
      await this.writeFileContent(saveFile, JSON.stringify(gameSave));
      return true;
    } catch (error) {
      console.error('保存游戏进度失败:', error);
      return false;
    }
  }

  // 加载游戏进度
  async loadGame(saveId: string): Promise<GameSave | null> {
    await this.ensureInitialized();
    try {
      const saveFile = path.join(GAME_SAVES_DIR, `save_${saveId}.json`);
      const content = await this.readFileContent(saveFile);
      return JSON.parse(content) as GameSave;
    } catch (error) {
      console.error('加载游戏进度失败:', error);
      return null;
    }
  }

  // 获取所有存档列表 - 修复文件列表获取方式
  async getSaveList(): Promise<{id: string, heroName: string, currentStage: number, timestamp: number}[]> {
    await this.ensureInitialized();
    try {
      // 使用opendir替代listFile
      const saveList = [];
      try {
        const dir = await fs.opendir(GAME_SAVES_DIR);
        let dirent;
        while ((dirent = await dir.read()) !== null) {
          if (dirent.isFile && dirent.name.endsWith('.json')) {
            try {
              const content = await this.readFileContent(path.join(GAME_SAVES_DIR, dirent.name));
              const save = JSON.parse(content) as GameSave;
              saveList.push({
                id: save.id,
                heroName: save.hero.name,
                currentStage: save.currentStage,
                timestamp: save.timestamp
              });
            } catch (fileError) {
              console.error(`读取存档文件失败 ${dirent.name}:`, fileError);
            }
          }
        }
        await dir.close();
      } catch (dirError) {
        console.error('读取存档目录失败:', dirError);
      }
      
      // 按时间戳降序排序
      return saveList.sort((a, b) => b.timestamp - a.timestamp);
    } catch (error) {
      console.error('获取存档列表失败:', error);
      return [];
    }
  }

  // 删除存档
  async deleteSave(saveId: string): Promise<boolean> {
    await this.ensureInitialized();
    try {
      const saveFile = path.join(GAME_SAVES_DIR, `save_${saveId}.json`);
      await fs.unlink(saveFile);
      return true;
    } catch (error) {
      console.error('删除存档失败:', error);
      return false;
    }
  }
}